﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[System.Serializable]
public class Boundary {

	public float xMin, xMax, zMin, zMax;

}

public class PlayerController : MonoBehaviour {

	// The rigidbody component attached to the 'Player' game object
	public Rigidbody rb;

	public float speed; 		// 'public' makes the property visible in the editor
	public float tilt;
	public Boundary boundary;

	public GameObject shot;
	public Transform shotSpawn;

	public float fireRate;

	private float nextFire;		// only needs to be visible within the class

	void Start () 
	{
		rb = GetComponent<Rigidbody> ();
	}

	void FixedUpdate() 
	{
//		print("Update triggered");
		float moveHorizontal = Input.GetAxis ("Horizontal");
		float moveVertical = Input.GetAxis ("Vertical");

		Vector3 movement = new Vector3 (moveHorizontal, 0.0f, moveVertical);
		rb.velocity = movement * speed;  // Spaceship can move out of the game area

		rb.position = new Vector3 (
			Mathf.Clamp (rb.position.x, boundary.xMin, boundary.xMax),
			0.0f,
			Mathf.Clamp (rb.position.z, boundary.zMin, boundary.zMax)
		);

		rb.rotation = Quaternion.Euler (0.0f, 0.0f, rb.velocity.x * -tilt);
	}

	void Update() // will be executed just before updating every frame
	{
		if (Input.GetButton ("Fire1") && Time.time > nextFire) {
			// update the time, keep control of the fire rate
			nextFire = Time.time + fireRate;
			Instantiate (shot, shotSpawn.position, shotSpawn.rotation);
//			AudioClip clip = GetComponent<AudioClip> ();
			AudioSource audio = GetComponent<AudioSource> ();
			audio.Play ();
		}
	}
}
